<template>
  <van-config-provider :theme-vars="themeVars" theme-vars-scope="global">
    <router-view v-slot="{ Component, route }">
      <transition :name="route.meta.transition as string">
        <keep-alive>
          <component :is="Component" :key="route.name" v-if="route.meta.keepAlive" />
        </keep-alive>
      </transition>
      <transition :name="route.meta.transition as string">
        <component :is="Component" :key="route.name" v-if="!route.meta.keepAlive" />
      </transition>
    </router-view>
    <global-sound ref="soundRef" />
    <Toaster
      position="top-center"
      :close-button="true"
      :expand="true"
      :toastOptions="{
        class: 'my-toast'
      }"
    />
  </van-config-provider>
</template>

<script lang="ts" setup>
import $bus from "@/utils/bus";
import { defineComponent, h, markRaw } from "vue";
import singleBetImg from "@/assets/images/single-bet.png";
import singleWinImg from "@/assets/images/single-win.png";
import { Toaster, toast } from "vue-sonner";
import type { ConfigProviderThemeVars } from "vant";
import { useUserStore } from "./store/modules/user";
import { storeToRefs } from "pinia";
import { netAvatar } from "@/utils/common";
import { SocketMsgType, SoundName } from "@/enums";
import { useServiceStore } from "./store/modules/service";
import { useRoomStore } from "./store/modules/room";

const themeVars = reactive<ConfigProviderThemeVars>({
  primaryColor: "#3976cb",
  successColor: "#60aa54",
  dangerColor: "#D03731",
  borderColor: "#E4E4E4"
});
window.isFirst = false;
window.sound = false;
const userStore = useUserStore();
const roomStore = useRoomStore();
const { token } = storeToRefs(userStore);
const serviceStore = useServiceStore();
const { serviceList } = storeToRefs(serviceStore);
const router = useRouter();
const soundRef = ref();
const route = useRoute();

const playSound = (name: SoundName) => {
  soundRef.value?.play(name);
};

// 客服通知
const KefuNotice = (data: KefuMsg, dismiss: Function) => {
  const service = serviceList.value.find(item => Number(item.UserId) == Number(data.user_id));
  console.log(service);
  if (!service) {
    serviceStore.actionServiceList(data.user_id);
  } else {
    const params = {
      ...service,
      LastMsg: data.content,
      LastMsgTime: data.time
    };
    if (route.path != "/admin/main/chat-room") {
      if (route.query.uid != service.UserId) {
        params.Count = service.Count! + 1;
        serviceStore.updateServiceItem(params);
      } else {
        params.Count = 0;
        serviceStore.updateServiceItem(params);
      }
    } else {
      params.Count = service.Count! + 1;
      serviceStore.updateServiceItem(params);
    }
  }
  // 监听客服
  let notification = `
  		<div class="flex justify-between items-center p-[15px]">
  			<div class="w-[40px] h-[40px] bg-[#fff] rounded-[40px] overflow-hidden">
  				<img class="w-[40px] h-[40px] block" src="${netAvatar(data.avatar)}"/>
  			</div>
  			<div class="flex-1 w-0 ml-[10px]">
  				<div class="leading-none text-[#000]">用户：${data.nick_name}</div>
  				<div class="mt-[8px] text-[#000] break-all">
  					<span>${data.msg_type == SocketMsgType.img_msg ? "【图片消息】" : data.content}</span>
  				</div>
  			</div>
  		</div>
  	`;
  playSound(SoundName.msgSound);
  return defineComponent({
    setup() {
      return () =>
        h("div", {
          innerHTML: notification,
          onClick: () => {
            dismiss();
            router.push(
              `/admin/main/chat-room?uid=${service?.UserId}&contentId=${service?.Id}&name=${
                service?.Note || service?.NickName || service?.Name
              }`
            );
          }
        });
    }
  });
};

// 上下分通知
const upDownJoinNotice = (data: SocketMsg, dismiss: Function) => {
  if (data.msg_type == SocketMsgType.down_socore || data.msg_type == SocketMsgType.up_score) {
    roomStore.applyCount += 1;
  }
  if (data.msg_type == SocketMsgType.joinroom) {
    roomStore.joinCount += 1;
  }
  // 监听上下分
  let notification = `
  		<div class="flex justify-between items-center p-[15px]">
  			<div class="w-[40px] h-[40px] bg-[#fff] rounded-[40px] overflow-hidden">
  				<img class="w-[40px] h-[40px] block" src="${netAvatar(data.avatar)}"/>
  			</div>
  			<div class="flex-[1] w-0 ml-[10px]">
  				<div class="leading-none text-[#000]">用户：${data.nick_name}</div>
  				<div class="mt-[8px] text-[#000]">
  					<span>${data.content}</span>
  				</div>
  			</div>
  		</div>
  	`;
  playSound(SoundName.newGroup);
  return defineComponent({
    setup() {
      return () =>
        h("div", {
          innerHTML: notification,
          onClick: () => {
            dismiss();
            // 上下分通知
            if (
              data.msg_type == SocketMsgType.down_socore ||
              data.msg_type == SocketMsgType.up_score
            ) {
              if (route.path == "/admin/apply/updown") {
                $bus.emit("update-updown-msg");
              } else {
                router.push("/admin/apply/updown");
              }
            }
            // 进房审核
            if (data.msg_type == SocketMsgType.joinroom) {
              if (route.path == "/admin/apply/join-room") {
                $bus.emit("update-join-room-msg");
              } else {
                router.push("/admin/apply/join-room");
              }
            }
          }
        });
    }
  });
};

// 其他提示
const otherNotice = (data: SocketMsg, dismiss: Function) => {
  let imgUrl = singleBetImg;
  if (data?.msg_type == SocketMsgType.single_bet || data?.msg_type == SocketMsgType.follow_up) {
    imgUrl = singleBetImg;
  } else {
    imgUrl = singleWinImg;
  }
  // 监听大额
  let notification = `
  		<div class="flex justify-between items-center p-[15px]" >
  			<div class="w-[50px] h-[50px] bg-[#fff] rounded-[50px] overflow-hidden">
  				<img class="w-[50px] h-[50px] block" src="${imgUrl}"/>
  			</div>
  			<div class="flex-[1] w-0 ml-[10px]">
  				${data.content}
  			</div>
  		</div>
  	`;
  playSound(SoundName.newNotice);
  return defineComponent({
    setup() {
      return () =>
        h("div", {
          innerHTML: notification,
          onClick: () => {
            dismiss();
            // 用户登录
            if (data.msg_type == SocketMsgType.follow_up) {
              if (route.path == "/admin/user/member") {
                $bus.emit("update-member-msg");
              } else {
                router.push("/admin/user/member");
              }
            } else {
              if (route.path == "/admin/report/notice") {
                $bus.emit("update-report-notice-msg");
              } else {
                router.push("/admin/report/notice");
              }
            }
          }
        });
    }
  });
};

const watchSocket = () => {
  $bus.on("kefu-msg-tip", data => {
    console.log(data);
    const toastId = toast(
      markRaw(
        KefuNotice(data, () => {
          toast.dismiss(toastId);
        })
      ),
      {
        duration: 30000000
      }
    );
  });
  $bus.on("updown-join-tip", data => {
    const toastId = toast(
      markRaw(
        upDownJoinNotice(data, () => {
          toast.dismiss(toastId);
        })
      ),
      {
        duration: 30000000
      }
    );
  });
  $bus.on("single-follow-tip", data => {
    const toastId = toast(
      markRaw(
        otherNotice(data, () => {
          toast.dismiss(toastId);
        })
      ),
      {
        duration: 30000000
      }
    );
  });
};

onMounted(() => {
  if (token.value) {
    userStore.actionUserInfo();
  }
  watchSocket();
  // 检查浏览器是否支持 Page Visibility API
  if (typeof document.hidden !== "undefined") {
    // 监听页面可见性变化事件
    document.addEventListener("visibilitychange", () => {
      if (document.hidden) {
        localStorage.setItem("idle-date", String(Date.now()));
      } else {
        const idleDate = localStorage.getItem("idle-date");
        const timestamp = Date.now(); // 当前时间戳
        // 比较两个时间戳的差异是否大于 10 分钟
        if (idleDate && Math.abs(timestamp - Number(idleDate)) > 600000) {
          location.reload();
        }
      }
    });
  } else {
    console.log("浏览器不支持 Page Visibility API");
  }
});
</script>
<style lang="scss">
#app,
.van-config-provider {
  width: 100%;
  max-width: 375px;
  margin: 0 auto;
  height: 100%;
  overflow: hidden;
  position: relative;
}
.animate__animated {
  --animate-duration: 0.8s;
}
.slide-left-enter-active,
.slide-left-leave-active,
.slide-right-enter-active,
.slide-right-leave-active {
  transition: transform 0.5s ease;
  position: absolute; /* 防止空白 */
  width: 100%; /* 确保页面组件占满整个宽度 */
}

.slide-left-enter-from,
.slide-right-leave-to {
  transform: translateX(100%);
}

.slide-left-leave-to,
.slide-right-enter-from {
  transform: translateX(-100%);
}
</style>
<style lang="css">
.page {
  @apply w-full h-full flex justify-between flex-col overflow-hidden bg-[#f2f1f6];
}
.page-main {
  @apply flex-1 overflow-auto;
}
.popup-box {
  width: 100%;
  padding: 0;
  max-width: 375px;
  left: calc((100vw - 375px) / 2) !important;
}
.item-active:active {
  @apply bg-[#f2f1f6];
}
.search-field {
  .van-search__content {
    background-color: #f1f4fb;
    .van-cell {
      height: 40px;
    }
  }
}
</style>
